package com.freshman_registration.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.freshman_registration.mapper.DormitoryMapper;
import com.freshman_registration.mapper.StudentMapper;


import com.freshman_registration.pojo.Dormitorys;
import com.freshman_registration.pojo.Students;
import com.freshman_registration.service.StudentService;

import com.freshman_registration.util.Result;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Service
@Slf4j
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private DormitoryMapper dormitoryMapper;
    //查询学生信息
    @Override
    public Result<Students> queryStudentByStudentId(String studentId) {
        Students student = studentMapper.queryStudentByStudentId(studentId);
        if(student != null){
            return Result.success(student);
        }
        return Result.fail("未查询到该学号的学生信息");
    }
    @Override
    public Result<?> insertStudent(Students student) {
        Students students = studentMapper.queryStudentByStudentId(student.getStudentId());
        if (students == null){
            student.setCreateTime(new Date());
            student.setPassword(SecureUtil.md5(student.getPassword()));
            int insert = studentMapper.insertStudent(student);
            if (insert > 0) {
                return Result.success("添加成功");
            }
            return Result.fail("添加失败");
        }
        return Result.fail("该学号已被注册");
    }
//修改学生信息
    @Override
    public Result<?> updateStudent(Students student) {

        if(student.getPassword()!=null && !"".equals(student.getPassword().trim()))
        {
            student.setPassword(SecureUtil.md5(student.getPassword()));
        }
        student.setUpdateTime(new Date());
        int update = studentMapper.updateStudent(student);
        if (update > 0) {
            return Result.success("修改成功");
        }
        return Result.fail("修改失败（可能学生id不存在或数据无变化");
    }
//删除学生信息
    @Override
    public Result<?> deleteStudent(Integer id) {
            int delete = studentMapper.deleteStudent(id);
            if (delete > 0) {
                return Result.success("删除成功");
            }
            return Result.fail("学生id不存在,删除失败");
        }

//分页查询所有学生信息
    @Override
    public Page queryAllStudents(Integer currentPage, Integer pageSize) {
      Page<Students> page = PageHelper.startPage(currentPage, pageSize);
        List<Students> students = studentMapper.queryAllStudents();
        return page;
    }


    //学生登录
    @Override
    public Result<Map<String,Object>> loginWithDorm(String studentId, String password){
        // 1. 查学生
        String md5Pwd = org.springframework.util.DigestUtils.md5DigestAsHex(password.getBytes());
        Students student = studentMapper.loginStudent(studentId, md5Pwd);
        if (student == null) {
            return Result.fail("学号或密码错误");
        }

        // 2. 查宿舍
        Dormitorys dorm = null;
        if (student.getDormId() != null) {
            dorm = dormitoryMapper.selectByPrimaryKey(student.getDormId());
        }

        // 3. 打包
        Map<String,Object> data = new HashMap<>(2);
        data.put("student", student);
        data.put("dorm", dorm == null ? new Dormitorys() : dorm);

        return Result.success(data);
    }

    //导出excel
    @Override
    public void exportExcel(HttpServletResponse response) {
        List<Students> students = studentMapper.queryAllStudents(); // 注意方法名小写
        try (ServletOutputStream os = response.getOutputStream();
             ExcelWriter writer = ExcelUtil.getWriter(true)) { // true 表示 .xlsx
            writer.write(students, true);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            String fileName = URLEncoder.encode("学生信息表", StandardCharsets.UTF_8.name());
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            writer.flush(os, true);
        } catch (IOException e) {
            log.error("导出Excel失败", e);
        }
    }

    //导入excel
    @Override
    public void importTemplate(HttpServletResponse response) throws IOException {
        //1.创建ExcelWriter对象
        ExcelWriter writer = ExcelUtil.getWriter();
        //2.设置导入模板字段
        Map<String, Object> row = new LinkedHashMap<>();
        row.put("id", "自动递增（无需填写）");
        row.put("student_id", "20250001（学号，必填）");
        row.put("password", "123456（初始密码，至少6位，必填）");
        row.put("name", "张三（姓名，必填）");
        row.put("id_card", "410XXXXXXXXXXXXXXX（身份证号，必填）");
        row.put("gender", "男（性别，选填：男/女）");
        row.put("phone", "139XXXXXXXX（手机号，必填）");
        row.put("college", "计算机学院（学院，必填）");
        row.put("major", "软件工程（专业，必填）");
        row.put("emergency_name", "李四（紧急联系人姓名，必填）");
        row.put("emergency_phone", "138XXXXXXXX（紧急联系人电话，必填）");
        row.put("dorm_id", "101（宿舍ID，必填）");
        row.put("allocate_time", "2025-09-01（分配时间，格式：yyyy-MM-dd，必填）");
        row.put("check_in_time", "2025-09-05（入住时间，格式：yyyy-MM-dd，可选）");
        row.put("info_submitted", "0（信息提交状态：0=未提交 1=已提交，无需填写）");
        row.put("report_status", "0（报到状态：0=未报到 1=已报到，无需填写）");
        row.put("account_status", "1（账号状态：1=启用 0=禁用，无需填写）");
        row.put("create_time", "2025-09-19（创建时间，格式：yyyy-MM-dd，无需填写）");
        row.put("update_time", "2025-09-19（更新时间，格式：yyyy-MM-dd，无需填写）");
        row.put("photo", "/profile/avatar.png（头像路径，可选）");
        row.put("class_name", "软件2501班（班级，必填）");
        row.put("counselor_name", "王五（辅导员姓名，必填）");
        row.put("counselor_phone", "137XXXXXXXX（辅导员电话，必填）");
        row.put("qq_group", "123456（QQ群号，必填）");
        row.put("native_place", "河南省郑州市（籍贯，必填）");
        row.put("home_address", "XX市XX区XX路XX号（家庭地址，必填）");
        row.put("contact_relation", "父子（与紧急联系人关系，必填）");
        List<Map<String, Object>> users = CollUtil.newArrayList(row);
        //3.将查询结果写入Excel
        writer.write(users, true);
        //4.设置浏览器响应格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户导入模板", "UTF-8");
        // 5.设置响应头信息
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        //获取输出流对象
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        //关闭流对象
        writer.close();
        IoUtil.close(out);
    }

    //根据学号修改学生信息
    @Override
    public Result<?> updateStudentByStudentId(Students student){
        int result = studentMapper.updateStudentByStudentId(student);
        return result > 0 ? Result.success() : Result.fail("修改失败");
    }


    //根据状态姓名学号分页
    @Override
    public PageInfo<Students> queryStudents(Integer accountStatus,String studentId ,String name, Integer currentPage, Integer pageSize) {
        // 1. 打印参数（确认currentPage和pageSize有值，不再是空）
        log.info("查询参数：accountStatus={},studentId={}, name={}, currentPage={}, pageSize={}",
                accountStatus,studentId, name, currentPage, pageSize);

        // 2. 设置分页（PageHelper会自动拦截后续的查询SQL，添加LIMIT分页）
        PageHelper.startPage(currentPage, pageSize);

        // 3. 执行查询（此时返回的List已被PageHelper处理为分页数据）
        List<Students> studentList = studentMapper.queryStudents(accountStatus,studentId,name);

        // 4. 封装为PageInfo（包含总条数、总页数等分页信息，方便前端使用）
        PageInfo<Students> pageInfo = new PageInfo<>(studentList);
        return pageInfo;
    }


    //根据id批量删除
    @Override
    public Result<?> deleteBatchStudent(List<Integer> ids) {
        int result = studentMapper.deleteBatchStudent(ids);
        if (result > 0) {
            return Result.success("删除成功");
        }
        return Result.fail("删除失败");
    }
    //状态按钮更新
    @Override
    public Result<Integer> updateStatusStudent(Integer id,String accountStatus) {
        // 1. 参数校验
        if (id == null || id <= 0) {
            return Result.fail("用户 ID 非法");
        }
        if (accountStatus == null || accountStatus.trim().isEmpty()) {
            return Result.fail("状态值不能为空");
        }
        // 2. 落库
        int rows = studentMapper.updateStatusStudent(id, accountStatus);
        if (rows == 0) {
            return Result.fail("用户不存在或状态已相同");
        }

        // 3. 返回受影响行数
        return Result.success(rows);
    }


    //修改密码
    @Override
    public Result<?> updatePassword(String studentId, String password) {
        if (password == null || password.trim().isEmpty()) {
            return Result.fail("密码不能为空");
        }

        // 对传入的密码进行MD5加密（注意：MD5安全性较低，建议使用BCrypt）
        String encryptedPassword = SecureUtil.md5(password.trim());

        // 落库（存储加密后的密码）
        int rows = studentMapper.updatePassword(studentId, encryptedPassword);
        if (rows == 0) {
            return Result.fail("用户不存在");
        }

        return Result.success(rows);
    }


    //更新头像
    @Override
    public Result<?> updatePhoto(String studentId, String photo) {
        int result = studentMapper.updatePhoto(studentId, photo);
        return result > 0 ? Result.success() : Result.fail("更新失败");
    }

}
